package com.kongyz.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * @author kongyz
 * @date 2018/7/21 09:53
 * @Description:
 */
public class EchoServer {
    private final int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public void start() throws InterruptedException {
        //2、创建并分配一个 NioEventLoopGroup 实例来处理事件的处理， 如接受新的连接和读/写数据
        NioEventLoopGroup group=new NioEventLoopGroup();
        try {
            //1、创建 ServerBootstrap 实例来引导服务器并随后绑定
            ServerBootstrap b=new ServerBootstrap();
            b.group(group)
                    .channel(NioServerSocketChannel.class)          //指定使用NIO的传输Channel
                    .localAddress(new InetSocketAddress(port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        //添加EchoServerHandler到Channel的ChannelPipeline
                        //如果有入站信息， 这个处理器将被通知
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
                                    .addLast(new EchoServerHandler());
                        }
                    });
            //绑定的服务器，sync等待服务器关闭；调用 sync() 的原因是当前线程阻塞
            ChannelFuture f=b.bind().sync();
            System.out.println(EchoServer.class.getName()+"启动并监听："+f.channel().localAddress());
            //关闭channel和块，直到它被关闭
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //关闭EnentLoopGroup，释放所有资源
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) {
        try {
            new EchoServer(8868).start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
